package cn.com.cifi.mars.util;

import cn.com.cifi.mars.entity.PriceApprovalCoreWarn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 类名称：PriceApprovalCoreWarnTemplate
 * 类描述：导出货值审批核心指标表
 *
 * @author yanboliu
 * @version 1.0.0
 */
@Slf4j
public class PriceApprovalCoreWarnTemplate {
    /**
     * 表格模板地址
     */
    private static final String TEMPLATE_PATH = "/template/price_approval_core_warn_template.xlsx";
    /**
     * 初始化文件
     */
    private XSSFWorkbook workbook;
    /**
     * 初始化表格
     */
    private XSSFSheet sheet;
    /**
     * 默认sheet索引
     */
    private int defaultSheetIndex = 0;
    /**
     * 数据开始行
     */
    private int dataBeginRow = 1;
    /**
     * 当前行标
     */
    private int currentDataRowCursor = dataBeginRow;
    /**
     * 单元格样式
     */
    private XSSFCellStyle cellStyle;
    /**
     * 文字样式1
     */
    private XSSFCellStyle cellStyle1;
    /**
     * 文字样式2
     */
    private XSSFCellStyle cellStyle2;
    /**
     * 文字样式3
     */
    private XSSFCellStyle cellStyle3;

    /**
     * 设置表格基本属性
     */
    public PriceApprovalCoreWarnTemplate() {

        try {
            InputStream tempInputStream = PriceApprovalCoreWarnTemplate.class.getResourceAsStream(TEMPLATE_PATH);
            if (tempInputStream != null) {
                workbook = new XSSFWorkbook(tempInputStream);
                sheet = workbook.getSheetAt(defaultSheetIndex);
                XSSFRow row = sheet.getRow(dataBeginRow);
                cellStyle1 = sheet.getRow(8).getCell(0).getCellStyle();
                cellStyle2 = sheet.getRow(1).getCell(2).getCellStyle();
                cellStyle3 = sheet.getRow(4).getCell(3).getCellStyle();

            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 批量插入行
     *
     * @param priceApprovalCoreWarns
     * @param sheetIndex
     */
    public synchronized void appendRows(List<PriceApprovalCoreWarn> priceApprovalCoreWarns, int sheetIndex) {

        sheet = workbook.getSheetAt(sheetIndex);
        for (PriceApprovalCoreWarn priceApprovalCoreWarn : priceApprovalCoreWarns) {
            switch (priceApprovalCoreWarn.getObjName()) {
                case "权益前货值（万元）":
                    modifyValue(priceApprovalCoreWarn);
                    this.currentDataRowCursor = 1;
                    cellStyle = cellStyle2;
                    break;
                case "权益前创造利润额（万元）":
                    modifyValue(priceApprovalCoreWarn);
                    this.currentDataRowCursor = 2;
                    cellStyle = cellStyle2;
                    break;
                case "权益后创造利润额（万元）":
                    modifyValue(priceApprovalCoreWarn);
                    this.currentDataRowCursor = 3;
                    cellStyle = cellStyle2;
                    break;
                case "创造利润率":
                    modifyValueToRate(priceApprovalCoreWarn);
                    this.currentDataRowCursor = 4;
                    cellStyle = cellStyle3;
                    break;
                case "非融IRR":
                    modifyValueToRate(priceApprovalCoreWarn);
                    this.currentDataRowCursor = 5;
                    cellStyle = cellStyle3;
                    break;
                case "非融静态投资回收期（月）":
                    modifyValue(priceApprovalCoreWarn);
                    this.currentDataRowCursor = 6;
                    cellStyle = cellStyle2;
                    break;
                default:
            }
            this.appendRow(priceApprovalCoreWarn);
        }

    }

    /**
     * 编辑数据格式
     *
     * @param priceApprovalCoreWarn
     */
    private void modifyValue(PriceApprovalCoreWarn priceApprovalCoreWarn) {
        priceApprovalCoreWarn.setInvestment(changeUnit1(priceApprovalCoreWarn.getInvestment()));
        priceApprovalCoreWarn.setStrategy(changeUnit1(priceApprovalCoreWarn.getStrategy()));
        priceApprovalCoreWarn.setPresident(changeUnit1(priceApprovalCoreWarn.getPresident()));
        priceApprovalCoreWarn.setBeforeData(changeUnit1(priceApprovalCoreWarn.getBeforeData()));
        priceApprovalCoreWarn.setAfterData(changeUnit1(priceApprovalCoreWarn.getAfterData()));
        priceApprovalCoreWarn.setAfterInvestment(changeUnit2(priceApprovalCoreWarn.getAfterInvestment()));
        priceApprovalCoreWarn.setAfterStrategy(changeUnit2(priceApprovalCoreWarn.getAfterStrategy()));
        priceApprovalCoreWarn.setAfterPresident(changeUnit2(priceApprovalCoreWarn.getAfterPresident()));
        priceApprovalCoreWarn.setAfterBefore(changeUnit2(subtract(priceApprovalCoreWarn.getAfterData(), priceApprovalCoreWarn.getBeforeData())));
    }

    /**
     * 减法运算
     *
     * @param value1
     * @param value2
     * @return
     */
    private String subtract(String value1, String value2) {
        BigDecimal b1 = StringUtils.isEmpty(value1) || StringUtils.equalsIgnoreCase(value1, "null") ? new BigDecimal("0") : new BigDecimal(value1);
        BigDecimal b2 = StringUtils.isEmpty(value2) || StringUtils.equalsIgnoreCase(value2, "null") ? new BigDecimal("0") : new BigDecimal(value2);
        return String.valueOf(b1.subtract(b2));
    }

    /**
     * 保留2位小数
     *
     * @param value
     * @return
     */
    private String changeUnit1(String value) {
        value = StringUtils.isEmpty(value) || StringUtils.equalsIgnoreCase(value, "null") ? "null" : String.valueOf(new DecimalFormat("#.00").format(Double.parseDouble(value)));
        return value;
    }

    /**
     * 四舍五入
     *
     * @param value
     * @return
     */
    private String changeUnit2(String value) {
        value = StringUtils.isEmpty(value) || StringUtils.equalsIgnoreCase(value, "null") ? "null" : String.valueOf(Math.round(Double.parseDouble(value)));
        return value;
    }

    /**
     * 编辑数据格式
     *
     * @param priceApprovalCoreWarn
     */
    private void modifyValueToRate(PriceApprovalCoreWarn priceApprovalCoreWarn) {
        priceApprovalCoreWarn.setAfterBefore(changeToRate((subtract(priceApprovalCoreWarn.getAfterData(), priceApprovalCoreWarn.getBeforeData()))));
        priceApprovalCoreWarn.setInvestment(changeToRate(priceApprovalCoreWarn.getInvestment()));
        priceApprovalCoreWarn.setStrategy(changeToRate(priceApprovalCoreWarn.getStrategy()));
        priceApprovalCoreWarn.setPresident(changeToRate(priceApprovalCoreWarn.getPresident()));
        priceApprovalCoreWarn.setBeforeData(changeToRate(priceApprovalCoreWarn.getBeforeData()));
        priceApprovalCoreWarn.setAfterData(changeToRate(priceApprovalCoreWarn.getAfterData()));
        priceApprovalCoreWarn.setAfterInvestment(changeToRate(priceApprovalCoreWarn.getAfterInvestment()));
        priceApprovalCoreWarn.setAfterStrategy(changeToRate(priceApprovalCoreWarn.getAfterStrategy()));
        priceApprovalCoreWarn.setAfterPresident(changeToRate(priceApprovalCoreWarn.getAfterPresident()));
    }

    /**
     * 换算成百分比
     *
     * @param value
     * @return
     */
    private String changeToRate(String value) {
        String divisionSign = "%";
        value = StringUtils.isEmpty(value) || StringUtils.equalsIgnoreCase(value, "null") ? "null" : String.format("%.2f", Double.parseDouble(value)).concat(divisionSign);
        return value;
    }

    /**
     * 插入行
     *
     * @param coreWarn
     */
    public synchronized void appendRow(PriceApprovalCoreWarn coreWarn) {
        XSSFRow row = sheet.getRow(currentDataRowCursor);
        if (row == null) {
            row = sheet.createRow(currentDataRowCursor);
        }
        int index = 1;
        //项目信息
        if (StringUtils.isNotEmpty(coreWarn.getProfitRate())) {
            coreWarn.setProfitRate(changeToRate(coreWarn.getProfitRate()));
            this.appendCell(row, index++, cellStyle1, coreWarn.getProfitRate());
        } else {
            index++;
        }

        this.appendCell(row, index++, cellStyle, coreWarn.getInvestment());
        this.appendCell(row, index++, cellStyle, coreWarn.getStrategy());
        this.appendCell(row, index++, cellStyle, coreWarn.getPresident());
        this.appendCell(row, index++, cellStyle, coreWarn.getBeforeData());
        this.appendCell(row, index++, cellStyle, coreWarn.getAfterData());
        this.appendCell(row, index++, cellStyle, coreWarn.getAfterInvestment());
        this.appendCell(row, index++, cellStyle, coreWarn.getAfterStrategy());
        this.appendCell(row, index++, cellStyle, coreWarn.getAfterPresident());
        this.appendCell(row, index++, cellStyle, coreWarn.getAfterBefore());


    }

    /**
     * 插入列
     *
     * @param row
     * @param index
     * @param value
     */
    public synchronized void appendCell(XSSFRow row, int index, XSSFCellStyle style, String value) {
        String divisionSign = "%";
        XSSFCell cell = row.getCell(index);
        if (cell == null) {
            cell = row.createCell(index);
        }
        cell.setCellStyle(style);
        if (StringUtils.isNotBlank(value) && value.endsWith(divisionSign)) {
            cell.setCellValue(value == null || StringUtils.equals(value, "null") ? "" : value);
        } else {
            ReportUtils.setCellValue(cell, value == null || StringUtils.equals(value, "null") ? "" : value);
        }
    }


    /**
     * 导出
     *
     * @param outputStream
     * @throws IOException
     */
    public void write(OutputStream outputStream) throws IOException {
        workbook.write(outputStream);
    }
}
